package com.peko.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author：Peko
 * @Description：自定义网关全局filter
 * @Date：Created in 9:59 2023/8/3
 */

@Configuration
public class CustomGlobalFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger("CustomGlobalFilter");

    /**
     * 类似于javaWeb doFilter
     * @param exchange 封装了 request response
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        log.info("经过全局Filter处理-------------------");
        Mono<Void> filter = chain.filter(exchange);
        log.info("响应回来Filter处理-------------------");

        return filter;
    }

    //order 排序  int数字：用来指定filter执行顺序   默认顺序按照自然数字进行排序
    //一个项目里可能会存在多个filter，包括配置文件配置的，还有这里的自定义Bean，这里可以定义执行顺序
    //返回-1，代表在所有filter执行之前执行
    @Override
    public int getOrder() {
        return 0;
    }
}
